package com.zj.jdbc3Batis.tools;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public abstract  class AbstractResultHandler implements ResultSetHandler {
    protected Class<?> clazz;
    protected Map<String, String> colomnToFieldMap = new HashMap<>();

    public AbstractResultHandler(Class<?> clazz) {
        this.clazz = clazz;
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            colomnToFieldMap.put(clazz.getName() + "." + fields[i].getName().toLowerCase(), fields[i].getName());
        }
        System.out.println(colomnToFieldMap);
    }

    public abstract Object handler(ResultSet rs);


    public boolean isWrapClass(Class clz) {
        if (clz.equals(String.class) || clz.equals(Date.class)) {
            return false;
        }
        return !clz.isPrimitive();
    }

    public Object putResultToSimpleType(ResultSet rs) {
        try {
            return rs.getObject( 1);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Object putResultToPOJOType(ResultSet rs, ResultSetMetaData metadata) {
        try {
            Object bean = clazz.newInstance();
            for (int i = 0; i < metadata.getColumnCount(); i++) {
                String coulmnName = metadata.getColumnName(i + 1).toLowerCase();//得到每列的列名
                Object coulmnData = rs.getObject(i + 1);
                String mapKey=clazz.getName() + "." + coulmnName.toLowerCase();
                String field = colomnToFieldMap.get(mapKey);
                if (field != null) {
                    Field f = clazz.getDeclaredField(field);//反射出类上列名对应的属性
                    f.setAccessible(true);
                    f.set(bean, coulmnData);
                }
            }
            return bean;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
